import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'WebsiteList',
  setup() {
    // 使用 Composition API 的方式定义响应式数据
    const store = useStore()
    const router = useRouter()
    
    // 数据定义
    const selectedCategory = ref(null)
    const sortOption = ref('createdAt')
    const filteredWebsites = ref([])
    const currentPage = ref(1)
    const itemsPerPage = ref(12)
    const showLoginDialog = ref(false)
    const loginUsername = ref('')
    const loginPassword = ref('')
    const loginError = ref('')
    const showAddForm = ref(false)
    const newWebsite = ref({
      id: null,
      name: '',
      url: '',
      description: '',
      category: '',
      createdAt: ''
    })
    const isCategoryPanelOpen = ref(false)
    const showMovieRecommendations = ref(false)
    const expandedMovieId = ref(null)
    const movieRecommendations = ref([])
    
    // 计算属性
    const websites = computed(() => store.getters.getAllWebsites)
    const categories = computed(() => store.getters.getCategories)
    const currentTheme = computed(() => store.getters.getCurrentTheme)
    const isAdmin = computed(() => store.getters.isAdmin)
    const totalPages = computed(() => Math.ceil(filteredWebsites.value.length / itemsPerPage.value))
    
    const paginatedWebsites = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage.value
      return filteredWebsites.value.slice(start, start + itemsPerPage.value)
    })
    
    const visiblePages = computed(() => {
      const pages = []
      let start = Math.max(1, currentPage.value - 2)
      let end = Math.min(totalPages.value, currentPage.value + 2)
      
      if (end - start < 4) {
        if (start === 1) {
          end = Math.min(totalPages.value, start + 4)
        } else {
          start = Math.max(1, end - 4)
        }
      }
      
      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      
      return pages
    })
    
    // 图片代理函数，解决防盗链问题
    const proxyImage = (url) => {
      if (!url) return ''
      // 使用多种代理服务尝试解决防盗链问题
      // 方法1: 使用 images.weserv.nl 服务
      return 'https://images.weserv.nl/?url=' + encodeURIComponent(url.replace(/^https?:\/\//, '')) + '&w=300&h=400&output=jpg'
    }
    
    // 获取影视描述样式
    const getMovieDescriptionStyle = (movieId) => {
      return {
        maxHeight: expandedMovieId.value === movieId ? '200px' : '0',
        overflow: 'hidden',
        transition: 'max-height 0.3s ease'
      }
    }
    
    // 检查电影是否展开
    const isMovieExpanded = (movieId) => {
      return expandedMovieId.value === movieId
    }
    
    // 切换影视详情显示
    const toggleMovieDetails = (id) => {
      if (expandedMovieId.value === id) {
        expandedMovieId.value = null
      } else {
        expandedMovieId.value = id
      }
    }
    
    // 跳转到豆瓣搜索页面
    const goToDoubanSearch = (title) => {
      const searchUrl = `https://search.douban.com/movie/subject_search?search_text=${encodeURIComponent(title)}`
      window.open(searchUrl, '_blank', 'noopener,noreferrer')
    }
    
    // 选择分类
    const selectCategory = (category) => {
      selectedCategory.value = category
      showMovieRecommendations.value = false
    }
    
    // 切换主题
    const changeTheme = (theme) => {
      store.dispatch('setTheme', theme)
      document.documentElement.setAttribute('data-theme', theme)
    }
    
    // 切换主题
    const toggleTheme = () => {
      changeTheme(currentTheme.value === 'light' ? 'dark' : 'light')
    }
    
    // 应用自定义主题样式
    const applyCustomThemeStyles = (theme) => {
      // 移除之前可能添加的样式
      const existingStyle = document.getElementById('custom-theme-styles')
      if (existingStyle) {
        existingStyle.remove()
      }
      
      if (theme === 'dark') {
        // 创建新的样式元素
        const style = document.createElement('style')
        style.id = 'custom-theme-styles'
        style.textContent = `
          body {
            background-color: #000000 !important;
            color: #e0e0e0;
          }
          
          .website-list {
            background-color: #000000;
          }
          
          .sidebar {
            background: #1a1a1a;
            border-right: 1px solid #333;
          }
          
          .filter-header {
            background-color: #2d2d2d;
          }
          
          .main-content {
            background-color: #000000;
          }
          
          .website-card {
            background: #1a1a1a;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.7);
            border: 1px solid #333;
          }
          
          .website-card h2 a {
            color: #ff7f7f;
          }
          
          .website-card:hover {
            border-color: #ff7f7f;
          }
          
          .category {
            background-color: #333;
            color: #e0e0e0;
          }
          
          .pagination {
            background-color: #1a1a1a;
          }
          
          .pagination-btn, .page-number {
            background-color: #2d2d2d;
            border: 1px solid #444;
            color: #e0e0e0;
          }
          
          .pagination-btn:hover:not(:disabled), 
          .page-number:hover:not(.active) {
            background-color: #444;
          }
          
          .page-number.active {
            background-color: #ff7f7f;
            border-color: #ff7f7f;
            color: #000;
          }
          
          .modal-content {
            background: #1a1a1a;
            border: 1px solid #333;
          }
          
          input, textarea, select {
            background-color: #2d2d2d;
            border: 1px solid #444;
            color: #e0e0e0;
          }
          
          input::placeholder {
            color: #aaa;
          }
          
          .header-controls {
            background: #1a1a1a;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 1rem;
            border: 1px solid #333;
          }
          
          .header {
            background: #1a1a1a;
            border: 1px solid #333;
          }
          
          .current-category {
            background: #1a1a1a;
            border: 1px solid #333;
          }
          
          .empty-state {
            background: #1a1a1a;
            border: 1px solid #333;
          }
          
          .filter-section li {
            background: #2d2d2d;
          }
          
          .filter-section li:hover,
          .filter-section li.active {
            background: linear-gradient(135deg, #ff7f7f 0%, #d32f2f 100%);
          }
          
          .admin-add-website .add-website-btn {
            background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
          }
          
          .theme-toggle-switch {
            background: linear-gradient(135deg, #4a4a4a 0%, #2d2d2d 100%);
          }
          
          .sorting {
            background: #1a1a1a;
            border: 1px solid #333;
          }
          
          .user-status .admin-badge {
            background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
            color: white;
          }
          
          /* 影视推荐样式 */
          .movie-card {
            background: #1a1a1a;
            border: 1px solid #333;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.7);
          }
          
          .movie-card:hover {
            border-color: #ff7f7f;
          }
          
          .movie-title {
            color: #ff7f7f;
          }
          
          .movie-toggle-btn {
            background: linear-gradient(135deg, #ff7f7f 0%, #d32f2f 100%);
            color: white;
          }
          
          .movie-toggle-btn:hover {
            background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
          }
        `
        document.head.appendChild(style)
      } else {
        // 为浅色主题添加优化的样式
        const style = document.createElement('style')
        style.id = 'custom-theme-styles'
        style.textContent = `
          body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
            color: #333;
          }
          
          .sidebar {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-right: 1px solid #e1e5eb;
          }
          
          .filter-header {
            background: linear-gradient(135deg, #f1f3f5 0%, #e9ecef 100%);
          }
          
          .main-content {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
          }
          
          .website-card {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
          }
          
          .category {
            background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
            color: #495057;
          }
          
          .pagination {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
          }
          
          .pagination-btn, .page-number {
            background: linear-gradient(135deg, #f1f3f5 0%, #e9ecef 100%);
            border: 1px solid #dee2e6;
            color: #495057;
          }
          
          .pagination-btn:hover:not(:disabled), 
          .page-number:hover:not(.active) {
            background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
          }
          
          .page-number.active {
            background: linear-gradient(135deg, #a8e6cf 0%, #8fd3b5 100%);
            border-color: #a8e6cf;
            color: #333;
          }
          
          .modal-content {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
          }
          
          input, textarea, select {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border: 1px solid #dee2e6;
            color: #333;
          }
          
          .header-controls {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            padding: 0.5rem 1rem;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 1rem;
          }
          
          .header {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
          }
          
          .current-category {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
          }
          
          .empty-state {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
          }
          
          /* 影视推荐样式 */
          .movie-card {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            border: 1px solid #dee2e6;
          }
          
          .movie-card:hover {
            border-color: #a8e6cf;
          }
          
          .movie-title {
            color: #333;
          }
          
          .movie-toggle-btn {
            background: linear-gradient(135deg, #a8e6cf 0%, #8fd3b5 100%);
            color: #333;
          }
          
          .movie-toggle-btn:hover {
            background: linear-gradient(135deg, #333 0%, #555 100%);
            color: white;
          }
        `
        document.head.appendChild(style)
      }
    }
    
    // 显示登录提示
    const showLoginPrompt = () => {
      showLoginDialog.value = true
      loginUsername.value = ''
      loginPassword.value = ''
      loginError.value = ''
    }
    
    // 关闭登录对话框
    const closeLoginDialog = () => {
      showLoginDialog.value = false
    }
    
    // 执行登录
    const performLogin = () => {
      // 验证管理员账户名和密码
      if (loginUsername.value === 'admin' && loginPassword.value === store.state.adminPassword) {
        store.dispatch('setAdminStatus', true)
        closeLoginDialog()
      } else {
        loginError.value = '用户名或密码错误'
      }
    }
    
    // 登出
    const logout = () => {
      store.dispatch('setAdminStatus', false)
    }
    
    // 编辑网站
    const editWebsite = (id) => {
      router.push('/admin/edit/' + id)
    }
    
    // 删除网站
    const deleteWebsite = (id) => {
      if (confirm('确定要删除这个网站吗？')) {
        store.dispatch('deleteWebsite', id)
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知日期'
      return new Date(dateString).toLocaleDateString('zh-CN')
    }
    
    // 应用筛选器
    const applyFilters = () => {
      let result = [...websites.value]
      
      // 应用分类筛选
      if (selectedCategory.value) {
        result = result.filter(website => (website.category || website.lei) === selectedCategory.value)
      }
      
      // 应用排序
      if (sortOption.value === 'name') {
        result.sort((a, b) => (a.name || '').localeCompare((b.name || ''), 'zh-CN'))
      } else {
        // 默认按创建时间排序（最新的在前）
        result.sort((a, b) => new Date(b.createdAt || b.creatTime) - new Date(a.createdAt || a.creatTime))
      }
      
      filteredWebsites.value = result
    }
    
    // 显示添加网站表单
    const showAddWebsiteForm = () => {
      // 初始化新网站对象
      newWebsite.value = {
        id: Date.now(), // 使用时间戳作为简单ID
        name: '',
        url: '',
        description: '',
        category: '',
        createdAt: new Date().toISOString()
      }
      showAddForm.value = true
    }
    
    // 关闭添加表单
    const closeAddForm = () => {
      showAddForm.value = false
    }
    
    // 添加网站
    const addWebsite = () => {
      if (newWebsite.value.name && newWebsite.value.description && newWebsite.value.category) {
        store.dispatch('addWebsite', newWebsite.value)
        closeAddForm()
      } else {
        alert('请填写所有必填字段')
      }
    }
    
    // 改变页面
    const changePage = (page) => {
      currentPage.value = page
    }
    
    // 获取分类下的网站数量
    const getCategoryCount = (category) => {
      return websites.value.filter(w => (w.category || w.lei) === category).length
    }
    
    // 格式化网站链接
    const formatWebsiteUrl = (url) => {
      if (!url) return '#'
      // 如果链接不包含协议，则添加 https://
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        url = 'https://' + url
      }
      
      try {
        // 验证 URL 格式是否正确
        new URL(url)
        return url
      } catch (e) {
        console.error('Invalid URL format:', url, e)
        return '#'
      }
    }
    
    // 打开网站链接
    const openWebsite = (url) => {
      const formattedUrl = formatWebsiteUrl(url)
      if (formattedUrl !== '#') {
        // 安全检查：确保链接是有效的
        try {
          const urlObj = new URL(formattedUrl)
          // 只允许 http 和 https 协议
          if (urlObj.protocol === 'http:' || urlObj.protocol === 'https:') {
            window.open(formattedUrl, '_blank', 'noopener,noreferrer')
          } else {
            console.warn('Blocked opening URL with potentially unsafe protocol:', formattedUrl)
            alert('该链接使用了不安全的协议，无法打开')
          }
        } catch (e) {
          console.error('Invalid URL format:', formattedUrl, e)
          alert('链接格式不正确，无法打开')
        }
      }
    }
    
    // 切换面板状态
    const toggleCategoryPanel = () => {
      isCategoryPanelOpen.value = !isCategoryPanelOpen.value
    }
    
    // 切换影视推荐显示
    const toggleMovieRecommendations = () => {
      showMovieRecommendations.value = !showMovieRecommendations.value
      selectedCategory.value = null
    }
    
    // 加载电影数据
    const loadMovieData = async () => {
      try {
        const response = await fetch('/douban1_movies.json')
        const movies = await response.json()
        
        // 转换数据格式以适配现有组件，并使用图片代理解决防盗链问题
        movieRecommendations.value = movies.map(movie => ({
          title: movie.title || '未知电影',
          image: proxyImage(movie.image),
          year: movie.year || movie.summary ? movie.summary.substring(0, 4) : '未知',
          director: movie.director || '未知',
          rating: movie.rating || '暂无评分',
          tags: [],
          description: movie.summary || movie.description || '暂无简介'
        }))
      } catch (error) {
        console.error('加载电影数据失败:', error)
        // 如果加载失败，使用原有的示例数据
        movieRecommendations.value = [
          {
            title: '肖申克的救赎',
            image: proxyImage('https://img3.doubanio.com/view/photo/s_ratio_poster/public/p480747492.jpg'),
            year: '1994',
            director: '弗兰克·德拉邦特',
            description: '银行家安迪被指控谋杀妻子及其情人，被判终身监禁。在狱中，他与囚犯瑞德建立了深厚的友谊，并逐渐展现出他对自由的渴望和对希望的坚持。',
            rating: '9.7',
            tags: ['剧情', '犯罪']
          },
          {
            title: '霸王别姬',
            image: proxyImage('https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2911205318.jpg'),
            year: '1993',
            director: '陈凯歌',
            description: '影片讲述了两位京剧演员段小楼与程蝶衣的人生经历和情感纠葛，反映了中国近现代史的变迁和传统文化的沉浮。',
            rating: '9.6',
            tags: ['剧情', '爱情', '同性']
          },
          {
            title: '阿甘正传',
            image: proxyImage('https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2372307693.jpg'),
            year: '1994',
            director: '罗伯特·泽米吉斯',
            description: '智商只有75的阿甘，凭借执着和善良，在人生各个阶段都取得了成功，见证了美国20世纪后半叶的历史变迁。',
            rating: '9.5',
            tags: ['剧情', '爱情']
          }
        ]
      }
    }
    
    // 组件挂载时执行
    onMounted(async () => {
      // 加载电影数据
      await loadMovieData()
      
      // 初始化存储
      await store.dispatch('initializeStore')
      applyFilters()
    })
    
    // 监听网站数据变化并重新应用筛选器
    // 在 Vue 3 中，我们可以使用 watch 来实现
    // 但由于这是一个重构，我们暂时保持原来的行为
    
    // 暴露给模板的数据和方法
    return {
      // 数据
      selectedCategory,
      sortOption,
      filteredWebsites,
      currentPage,
      itemsPerPage,
      showLoginDialog,
      loginUsername,
      loginPassword,
      loginError,
      showAddForm,
      newWebsite,
      isCategoryPanelOpen,
      showMovieRecommendations,
      expandedMovieId,
      movieRecommendations,
      
      // 计算属性
      websites,
      categories,
      currentTheme,
      isAdmin,
      totalPages,
      paginatedWebsites,
      visiblePages,
      
      // 方法
      proxyImage,
      getMovieDescriptionStyle,
      isMovieExpanded,
      toggleMovieDetails,
      goToDoubanSearch,
      selectCategory,
      changeTheme,
      toggleTheme,
      applyCustomThemeStyles,
      showLoginPrompt,
      closeLoginDialog,
      performLogin,
      logout,
      editWebsite,
      deleteWebsite,
      formatDate,
      applyFilters,
      showAddWebsiteForm,
      closeAddForm,
      addWebsite,
      changePage,
      getCategoryCount,
      formatWebsiteUrl,
      openWebsite,
      toggleCategoryPanel,
      toggleMovieRecommendations
    }
  }
}